//
//  UIViewController+Track.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/10/9.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "UIViewController+Track.h"
#import <objc/runtime.h>
#import <UMMobClick/MobClick.h>

@implementation UIViewController (Track)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        // viewWillAppear
        SEL originalSelector1 = @selector(viewWillAppear:);
        SEL swizzledSelector1 = @selector(mgTrack_viewWillAppear:);
        
        // viewWillDisappear
        SEL originalSelector2 = @selector(viewWillDisappear:);
        SEL swizzledSelector2 = @selector(mgTrack_viewWillDisappear:);
        
        // hook系统API
        Method originalMethod1 = class_getInstanceMethod(class, originalSelector1);
        Method swizzledMethod1 = class_getInstanceMethod(class, swizzledSelector1);
        
        Method originalMethod2 = class_getInstanceMethod(class, originalSelector2);
        Method swizzledMethod2 = class_getInstanceMethod(class, swizzledSelector2);
        
        BOOL didAddMethod1 = class_addMethod(class,originalSelector1,method_getImplementation(swizzledMethod1),method_getTypeEncoding(swizzledMethod1));
        BOOL didAddMethod2 = class_addMethod(class,originalSelector2,method_getImplementation(swizzledMethod2),method_getTypeEncoding(swizzledMethod2));

        if (didAddMethod1) {
            class_replaceMethod(class,swizzledSelector1,method_getImplementation(originalMethod1),method_getTypeEncoding(originalMethod1));
        } else {
            method_exchangeImplementations(originalMethod1, swizzledMethod1);
        }
        
        if (didAddMethod2) {
            class_replaceMethod(class, swizzledSelector2, method_getImplementation(originalMethod2), method_getTypeEncoding(originalMethod2));
        } else {
            method_exchangeImplementations(originalMethod2, swizzledMethod2);
        }
    });
}

#pragma mark - Method Swizzling

- (void)mgTrack_viewWillAppear:(BOOL)animated {
    [self mgTrack_viewWillAppear:animated];
    if (self.title || self.navigationItem.title) {
        [MobClick beginLogPageView:self.title ? self.title : self.navigationItem.title];
    } else {
        [MobClick beginLogPageView:NSStringFromClass([self class])];
    }
}

- (void)mgTrack_viewWillDisappear:(BOOL)animated {
    [self mgTrack_viewWillDisappear:animated];
    if (self.title || self.navigationItem.title) {
        [MobClick endLogPageView:self.title ? self.title : self.navigationItem.title];
    } else {
        [MobClick endLogPageView:NSStringFromClass([self class])];
    }
}

@end
